package com.cn.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.cn.common.HttpUtils;
import com.cn.http.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 暴露给业务方的Http接口前端控制器
 * 配置为多实例
 * Created by YangJie on 2016/4/13.
 */
@Controller
@Scope("prototype")
public class HttpBusinessController {

    private final static Logger LOGGER = LoggerFactory.getLogger(HttpBusinessController.class) ;

    @Autowired
    HttpClients httpClients ;

    /**
     * 业务方请求入口
     * @param ciphertext
     */
    @RequestMapping(value = "/httpAction!httpchannel.action", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8")
    @ResponseBody
    public String httpChannel(@RequestParam(value = "ciphertext", required = false) String ciphertext,
                              HttpServletRequest request) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("request param: ciphertext: {}", ciphertext);
        }

        JSONObject jsonObject = new JSONObject();
        try {
            String result = httpClients.httpClientsChannel(ciphertext, HttpUtils.getIpAddr(request));

            if ("success".equals(result)) {
                jsonObject.put("resultCode", "1");
                jsonObject.put("errorDesc", "发送成功");
            } else {
                jsonObject.put("resultCode", "2");
                jsonObject.put("errorDesc", result);
            }

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("reslut:" + jsonObject.toString());
            }

            return jsonObject.toJSONString() ;

        } catch (Exception e) {
            LOGGER.error("发生异常，错误信息： ciphertext: {}, errMsg: {}", ciphertext, e.getMessage(), e);
        }
        return "{\"resultCode\":\"1\";\"errorDesc\":\"json异常\"}" ;
    }
}
